package org.example.liuy.service.session;

import lombok.extern.slf4j.Slf4j;
import org.example.liuy.service.MonitoringService;

import java.util.concurrent.CompletableFuture;

/**
 * 智能会话服务 - 综合所有优化策略
 * 应对千亿级用户访问场景
 */
@Slf4j
public class IntelligentSessionService {

    private final IntelligentSessionManager sessionManager;
    private final IntelligentQueueManager queueManager;
    private final MonitoringService monitoringService;

    public IntelligentSessionService(MonitoringService monitoringService) {
        this.monitoringService = monitoringService;
        this.sessionManager = new IntelligentSessionManager(monitoringService);
        this.queueManager = new IntelligentQueueManager();
    }

    /**
     * 智能创建会话 - 自适应处理各种负载情况
     */
    public CompletableFuture<String> createSession(Integer customerId) {
        return monitoringService.monitor("session.create.intelligent", () -> {
            // 首先尝试直接创建（快速路径）
            String directResult = sessionManager.createSession(customerId);

            // 如果没有被限流，直接返回结果
            if (directResult != null && !directResult.startsWith("REJECTED")) {
                CompletableFuture<String> future = new CompletableFuture<>();
                future.complete(directResult);
                return future;
            }

            // 如果被限流，进入队列处理（慢速路径）
            log.debug("Session creation throttled for customer: {}, queuing request", customerId);
            return queueManager.submitSessionRequest(customerId, determinePriority(customerId));
        });
    }

    /**
     * 智能验证会话
     */
    public IntelligentSessionManager.SessionValidationResult validateSession(String sessionKey, Integer customerId) {
      return sessionManager.validateSession(sessionKey, customerId);
    }

    /**
     * 获取客户ID
     */
    public Integer getCustomerIdFromSession(String sessionKey) {
        return sessionManager.getCustomerIdFromSession(sessionKey);
    }

    /**
     * 根据客户特征确定处理优先级
     */
    private int determinePriority(Integer customerId) {
        // 这里可以实现更复杂的优先级逻辑
        // 例如：VIP客户高优先级，新客户普通优先级，机器人低优先级等

        // 简单示例：根据客户ID尾数确定优先级
        int idMod = Math.abs(customerId) % 10;
        if (idMod < 2) {
            return 1; // 20% 高优先级
        } else if (idMod < 7) {
            return 2; // 50% 普通优先级
        } else {
            return 3; // 30% 低优先级
        }
    }

    /**
     * 获取系统状态
     */
    public String getSystemStatus() {
        StringBuilder status = new StringBuilder();
        status.append("=== Intelligent Session Service Status ===\n");
        status.append(sessionManager.getStatistics()).append("\n");
        status.append("Queue Manager: Active\n");
        return status.toString();
    }

    public void start() {
        sessionManager.startCleanupTask();
        log.info("Intelligent Session Service started");
    }

    public void stop() {
        queueManager.shutdown();
        sessionManager.stop();
        log.info("Intelligent Session Service stopped");
        log.info("Final status:\n{}", getSystemStatus());
    }
}